//
//  SignInUpViewController.swift
//  placepic
//
//  Created by elesahich on 2020/09/05.
//  Copyright © 2020 elesahich. All rights reserved.
//

import UIKit

class SignInUpViewController: UIViewController {
    
    @IBOutlet weak var firstStackView: UIStackView!
    @IBOutlet weak var phoneNumberLabel: UILabel!
    @IBOutlet weak var phoneNumberTextField: UITextField!
    @IBOutlet weak var phoneExplainLabel: UILabel!
    @IBOutlet weak var loginButton: UIButton!
    
    @IBOutlet weak var secondStackView: UIStackView!
    @IBOutlet weak var certificateNumberLabel: UILabel!
    @IBOutlet weak var certificateTextField: UITextField!
    @IBOutlet weak var certificateExplainLabel: UILabel!
    @IBOutlet weak var startButton: UIButton!
    @IBOutlet weak var termsButton: UIButton!
    @IBOutlet weak var privacyButton: UIButton!
    @IBOutlet weak var privacyStacView: UIStackView!
    
    var firstButtonFlag = false
    var counter = 300
    var timer: Timer?
    
    var constraints: [NSLayoutConstraint] = []
    
    let minuteLabel: UILabel = {
        let label = UILabel()
        label.text = "05:00"
        label.font = UIFont.systemFont(ofSize: 15)
        label.textColor = UIColor.gray60
        label.translatesAutoresizingMaskIntoConstraints = false
        return label
    }()
    
    let statusBar: UIView = {
        let view = UIView()
        view.frame = CGRect.zero
        view.backgroundColor = UIColor.blueGray50
        view.translatesAutoresizingMaskIntoConstraints = false
        return view
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupNavigationBar()
        setupFirstStackView()
        setupSecondStackView()
        setupCountdownLabel()
        setupAttributeButtons()
        addTargetToTextFields()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        makeInitialProgressBar()
        makeAnimate()
    }
    
    @IBAction func sendNextButtonAction(_ sender: Any) {
        guard let vc = storyboard?.instantiateViewController(identifier: "RegisterGroupViewController")
            as? RegisterGroupViewController else { return
        }
        navigationController?.pushViewController(vc, animated: true)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        self.view.reloadInputViews()
        self.loginButton.layoutIfNeeded()
    }
}

// MARK: - Transform
extension SignInUpViewController {
    
    func makeInitialProgressBar() {
        self.view.addSubview(statusBar)

        constraints = [
            statusBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant:  0),
            statusBar.bottomAnchor.constraint(equalTo: firstStackView.topAnchor, constant: 0),
            statusBar.heightAnchor.constraint(equalToConstant: 1.5),
            statusBar.widthAnchor.constraint(equalToConstant: 0)
        ]
        NSLayoutConstraint.activate(constraints)
    }
    
    func makeAnimate() {
        let firstTransform = CGAffineTransform(translationX: 0, y: -300)
        let secondTransform = CGAffineTransform(translationX: 0, y: -500)
        let thirdTransform = CGAffineTransform(translationX: 0, y: -700)

        firstStackView.transform = firstTransform
        firstStackView.alpha = 0
        secondStackView.transform = secondTransform
        secondStackView.alpha = 0
        privacyStacView.transform = thirdTransform
        privacyStacView.alpha = 0
        
        NSLayoutConstraint.deactivate(constraints)
        
        constraints = [
            statusBar.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant:  0),
            statusBar.bottomAnchor.constraint(equalTo: firstStackView.topAnchor, constant: 0),
            statusBar.heightAnchor.constraint(equalToConstant: 1.5),
            statusBar.widthAnchor.constraint(equalToConstant: view.frame.width / 3 - 10)
        ]
        NSLayoutConstraint.activate(constraints)

        UIView.animate(withDuration: 1.5,
                       delay: 0.2,
                       usingSpringWithDamping: 1,
                       initialSpringVelocity: 1,
                       options: .curveEaseOut,
                       animations: {
                        self.view.layoutIfNeeded()
        }, completion: nil)
        UIView.animate(withDuration: 1.5,
                       delay: 0.9,
                       usingSpringWithDamping: 1,
                       initialSpringVelocity: 1,
                       options: .curveEaseOut,
                       animations: {
                        self.firstStackView.transform = .identity
                        self.firstStackView.alpha = 1
        }, completion: nil)
        UIView.animate(withDuration: 1.8,
                       delay: 1.3,
                       usingSpringWithDamping: 1,
                       initialSpringVelocity: 1,
                       options: .curveEaseOut,
                       animations: {
                        self.secondStackView.transform = .identity
                        self.privacyStacView.transform = .identity
                        self.secondStackView.alpha = 1
                        self.privacyStacView.alpha = 1
        }, completion: nil)
    }
}

//MARK: - CountDown Logic / Setting
extension SignInUpViewController {
    
    func setupCountdownLabel() {
        certificateTextField.addSubview(minuteLabel)
        certificateTextField.bringSubviewToFront(minuteLabel)
        
        let constraints = [
            minuteLabel.topAnchor.constraint(equalTo: certificateTextField.topAnchor, constant: 13),
            minuteLabel.trailingAnchor.constraint(equalTo: certificateTextField.trailingAnchor, constant: -12),
            minuteLabel.bottomAnchor.constraint(equalTo: certificateTextField.bottomAnchor, constant: -13),
            minuteLabel.widthAnchor.constraint(equalToConstant: 44)
        ]
        NSLayoutConstraint.activate(constraints)
        minuteLabel.isHidden = true
    }
    
    func startTimer() {
        guard timer == nil else { return }
        minuteLabel.isHidden = false
        
        timer = Timer.scheduledTimer(timeInterval: 1.0,
                             target: self,
                             selector: #selector(self.updateTimer),
                             userInfo: nil,
                             repeats: true)
    }
    
    func stopTimer() {
        timer?.invalidate()
        timer = nil
        counter = 300
    }
    
    @objc
    func updateTimer() {
        if counter > 0 {
            let minutes = String(describing: counter / 60)
            let seconds = counter % 60 > 9
                ? String(describing: counter % 60)
                : "0" + String(describing: counter % 60)
            minuteLabel.text = "0" + minutes + ":" + seconds
            counter -= 1
        } else {
            stopTimer()
        }
    }
}

// MARK: - Setup TextField, privacy StackView
extension SignInUpViewController {
    
    private func setupAttributeButtons() {
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.systemFont(ofSize: 12),
            .foregroundColor: UIColor.gray60,
            .underlineStyle: NSUnderlineStyle.single.rawValue
        ]
        let attributeString = NSMutableAttributedString(string: "이용약관",
                                                        attributes: attributes)
        let privacyAttributedString = NSMutableAttributedString(string: "개인정보취급방침",
                                                                
                                                                      attributes: attributes)
        termsButton.setAttributedTitle(attributeString, for: .normal)
        privacyButton.setAttributedTitle(privacyAttributedString, for: .normal)
        
    }

    private func addTargetToTextFields() {
        phoneNumberTextField.addTarget(self,
                                       action: #selector(changeLoginButtonActions),
                                       for: .allEditingEvents)
        loginButton.addTarget(self,
                              action: #selector(changeLoginButton),
                              for: .touchUpInside)
        
        certificateTextField.addTarget(self,
                                       action: #selector(changeButtonActions),
                                       for: .allEditingEvents)
    }
    
    @objc
    func changeLoginButton() -> Void {
        if firstButtonFlag == false {
            if timer?.isValid ?? false { stopTimer() }
            
            startTimer()
            loginButton.backgroundColor = UIColor.gray90
            loginButton.layer.borderColor = UIColor.gray90.cgColor
            loginButton.layer.borderWidth = 1.5
            loginButton.setTitle("인증문자 다시 받기", for: .normal)
            loginButton.setTitleColor(UIColor.white, for: .normal)
            firstButtonFlag = true
            
            DispatchQueue.main.asyncAfter(deadline: .now() + 30,
                                          execute: { [weak self] in
                self?.firstButtonFlag = false
            })
            
        } else {
            let alertViewController = UIAlertController(title: "주의",
                                                        message: "30초 후에 인증문자를 다시 받을 수 있습니다.",
                                                        preferredStyle: .alert)
            let action = UIAlertAction(title: "확인", style: .cancel, handler: nil)
            alertViewController.addAction(action)
            self.present(alertViewController, animated: true, completion: nil)
        }
    }
    
    @objc
    func changeLoginButtonActions() -> Void {
        if phoneNumberTextField.hasText {
            phoneNumberTextField.layer.borderColor = UIColor.gray70.cgColor
            phoneNumberTextField.layer.borderWidth = 1.5
            phoneNumberTextField.backgroundColor = UIColor.white
        } else {
            phoneNumberTextField.backgroundColor = UIColor.blueGray10
            phoneNumberTextField.layer.borderColor = UIColor.blueGray10.cgColor
        }
    }
    
    @objc
    func changeButtonActions() -> Void {
        if certificateTextField.hasText {
            certificateTextField.layer.borderColor = UIColor.gray70.cgColor
            certificateTextField.layer.borderWidth = 1.5
            certificateTextField.backgroundColor = UIColor.white
            startButton.backgroundColor = UIColor.warmPink
            startButton.layer.borderColor = UIColor.warmPink.cgColor
            startButton.layer.borderWidth = 1.5
            startButton.setTitle("동의하고 시작하기", for: .normal)
            startButton.setTitleColor(UIColor.white, for: .normal)
        } else {
            certificateTextField.backgroundColor = UIColor.blueGray10
            certificateTextField.layer.borderColor = UIColor.blueGray10.cgColor
            startButton.backgroundColor = UIColor.blueGray10
            startButton.layer.borderColor = UIColor.blueGray10.cgColor
            startButton.setTitleColor(UIColor.gray70, for: .normal)
        }
    }
        
    private func setupFirstStackView() {
        phoneNumberLabel.text = "핸드폰 번호"
        phoneNumberLabel.font = UIFont.boldSystemFont(ofSize: 15)
        phoneNumberLabel.textColor = UIColor.gray90
        
        let attributedString = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15),
                                NSAttributedString.Key.foregroundColor: UIColor.blueGray30,
        ]
        phoneNumberTextField.setLeftPaddingPoints(10)
        phoneNumberTextField.attributedPlaceholder = NSAttributedString(string: "핸드폰 번호를 입력해주세요", attributes: attributedString)
        phoneNumberTextField.backgroundColor = UIColor.blueGray10
        phoneNumberTextField.layer.cornerRadius = 8
        phoneNumberTextField.layer.borderColor = UIColor.blueGray10.cgColor
        phoneNumberTextField.layer.borderWidth = 1
        phoneNumberTextField.clipsToBounds = true
        phoneNumberTextField.delegate = self
        
        phoneExplainLabel.font = UIFont.systemFont(ofSize: 9)
        phoneExplainLabel.textColor = UIColor.blueGray80
        phoneExplainLabel.text = "핸드폰 번호만으로 가입이 완료됩니다. 번호는 안전하게 보관되며 공개되지 않습니다."
        
        loginButton.layer.cornerRadius = 8
        loginButton.backgroundColor = UIColor.blueGray10
        loginButton.setTitle("로그인", for: .normal)
        loginButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
        loginButton.setTitleColor(UIColor.gray70, for: .normal)
    }
  
    private func setupSecondStackView() {
        certificateNumberLabel.text = "인증번호"
        certificateNumberLabel.font = UIFont.boldSystemFont(ofSize: 15)
        certificateNumberLabel.textColor = UIColor.gray90
        
        let attributedString = [NSAttributedString.Key.font: UIFont.boldSystemFont(ofSize: 15),
                                NSAttributedString.Key.foregroundColor: UIColor.blueGray30,
        ]
        certificateTextField.setLeftPaddingPoints(10)
        certificateTextField.attributedPlaceholder = NSAttributedString(string: "인증번호를 입력해주세요", attributes: attributedString)
        certificateTextField.backgroundColor = UIColor.blueGray10
        certificateTextField.layer.cornerRadius = 8
        certificateTextField.layer.borderColor = UIColor.blueGray10.cgColor
        certificateTextField.layer.borderWidth = 1
        certificateTextField.clipsToBounds = true
        certificateTextField.delegate = self
        
        certificateExplainLabel.font = UIFont.systemFont(ofSize: 9)
        certificateExplainLabel.textColor = UIColor.blueGray80
        certificateExplainLabel.text = "5분내에 인증번호 입력을 완료해주세요"
        
        startButton.layer.cornerRadius = 8
        startButton.backgroundColor = UIColor.blueGray10
        startButton.setTitleColor(UIColor.gray70, for: .normal)
        startButton.setTitle("동의하고 그룹 찾으러 떠나기", for: .normal)
        startButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16)
    }
    
    private func setupNavigationBar() {
        guard let navigationBar = self.navigationController?.navigationBar else { return }
        
        navigationBar.isTranslucent = true
        navigationBar.backgroundColor = UIColor.clear
        navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default)
        navigationBar.shadowImage = UIImage()
        
        let title: UILabel = {
            let label = UILabel()
            label.text = "회원가입/로그인"
            label.font = .boldSystemFont(ofSize: 18)
            label.textColor = UIColor.gray90
            return label
        }()
        
        let backButton: UIButton = {
            let bt = UIButton()
            bt.setImage(UIImage(named: "backArrowIc"), for: .normal)
            return bt
        }()
        
        backButton.addTarget(self,
                             action: #selector(dismissVC),
                             for: .touchUpInside)

        navigationItem.leftBarButtonItem = UIBarButtonItem(customView: backButton)
        navigationItem.titleView = title
    }
    
    @objc
    private func dismissVC() {
        self.navigationController?.popViewController(animated: true)
    }
}


extension SignInUpViewController: UITextFieldDelegate {
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == phoneNumberTextField {
            phoneNumberTextField.resignFirstResponder()
        } else {
            certificateTextField.resignFirstResponder()
        }
        return true
    }
}

